import React from "react";
import {DeepMap, FieldError, Path, RegisterOptions, UseFormRegister,} from "react-hook-form"
import {get} from 'lodash'
import {ErrorMessage} from "@hookform/error-message"
import Input, {TypeInputProps} from "@/components/ui/Input/Input";
import FormErrorMessage from "@/components/ui/Forms/FormElements/FormErrorMessage";
import styles from "./FormInput.module.css"

export type TypeFormInputProps<TFormValues> = {
    name: Path<TFormValues>,
    rules?: RegisterOptions,
    register?: UseFormRegister<TFormValues | any>,
    errors?: Partial<DeepMap<TFormValues, FieldError>>,
} & Omit<TypeInputProps, 'name'>

export default function FormInput<TFormValues extends Record<string, unknown>>(
    {
        name,
        register,
        rules,
        errors,
        ...props
    }: TypeFormInputProps<TFormValues>): React.JSX.Element {
    const errorMessages = get(errors, name)
    const hasError = !!(errors && errorMessages)

    return (
        <div className={styles.formInput}>
            <Input
                name={name as string}
                {...props}
                {...(register && register(name, rules))}
            />
            <ErrorMessage
                errors={errors}
                name={name as any}
                render={({message}) => (
                    <FormErrorMessage>{message}</FormErrorMessage>
                )}
            />
        </div>

    )
}
